#include "DeviceState.h"
#include "media/sys_audio.h"
#include "log.h"
#include <fstream>
#include <iomanip>
#include <iostream>
#include <openssl/md5.h>
#include <sstream>

#define TAG "DeviceState"

void DeviceState::Initialize(int argc, char* argv[]) {
    // 默认路径
    std::string defaultPath = "/overlay/appA";
    appFilePath = defaultPath;

    for (int i = 1; i < argc; ++i) {
        if (std::string(argv[i]) == "--data-path" && i + 1 < argc) {
            appFilePath = argv[i + 1];
        }
    }

    initSerialNumber("/sys/class/sunxi_info/sys_info");

    audioFilePath = appFilePath + "/sys_media/";
    SysAudio::getInstance().SetSysAudioPath(audioFilePath);
    SysAudio::getInstance().Index1_OperationSuccess();
}

bool DeviceState::initSerialNumber(const std::string& sysInfoPath) {
    std::ifstream file(sysInfoPath);
    if (!file.is_open()) {
        std::cerr << "Failed to open " << sysInfoPath << '\n';
        return false;
    }

    std::string line;
    std::string sunxiSerialHex;    // 32 hex chars
    while (std::getline(file, line)) {
        constexpr char key[] = "sunxi_serial";
        auto pos = line.find(key);
        if (pos != std::string::npos) {
            // 格式:  sunxi_serial : 001122...
            std::istringstream iss(line.substr(pos + sizeof(key) - 1));
            char colon;
            iss >> colon >> sunxiSerialHex;    // 读取冒号后的串
            break;
        }
    }
    if (sunxiSerialHex.size() != 32) {
        std::cerr << "sunxi_serial not found or invalid\n";
        return false;
    }

    // 1️⃣ 32-char hex → 16 byte 二进制
    std::array<unsigned char, 16> snBytes{};
    for (size_t i = 0; i < snBytes.size(); ++i) {
        snBytes[i] = static_cast<unsigned char>(std::stoi(sunxiSerialHex.substr(i * 2, 2), nullptr, 16));
    }

    // 2️⃣ 计算 MD5
    std::array<unsigned char, MD5_DIGEST_LENGTH> md5{};
    MD5(snBytes.data(), snBytes.size(), md5.data());

    // 3️⃣ 取前 10 byte → 转 20 hex 字符
    std::ostringstream oss;
    for (size_t i = 0; i < 10; ++i) {
        oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(md5[i]);
    }
    serialNumber = oss.str();    // 赋值到类成员

    LOG_I(TAG, "serialNumber: %s", serialNumber.c_str());

    return true;
}